Ipywidgets

ipywidgets is a Python package providing interactive widgets for Jupyter notebooks.


In [ ]:
from __future__ import print_function
from ipywidgets import widgets

Text example

This example shows a text box. The widget handler just receives the text and prints it out.


In [ ]:
from IPython.display import display

def handle_submit(sender):
    print("Submitted:", text.value)
    
text = widgets.Text()
display(text)
text.on_submit(handle_submit)

Interact

interact(function, variable) creates a widget to modify the variable and binds it to the passed funcion. The widget type that is created depends on the type of the passed variable.

Note that the name of the variable given in the argument to interact must be the same as its name as given as argument to the handler function


In [ ]:
def doit(n):
    'receive the result of the widget in the function, and do sometthing with it'
    print("processed:", n*2+1)
    
widgets.interact(doit, n=[1, 2, 3]);
widgets.interact(doit, n=(0,1,0.1));

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
import math

In [ ]:
t = np.arange( 0.0, 1.0, 0.01)

def myplot( factor ):
    plt.plot( t, np.sin(2*math.pi*t*factor) )
    plt.show()
    
widgets.interact( myplot, factor=(0, 10, 2) );

In [ ]:
def do_something( fruit="oranges" ):
    print("Selected: [",fruit,"]")
    
widgets.interact(do_something, fruit=['apples','pears', 'oranges']);

Boxes


In [ ]:
from ipywidgets.widgets import (
    Button, HBox, VBox, Text, Textarea, Checkbox, IntSlider, 
    Controller, Dropdown, ColorPicker)
from ipywidgets import Layout

area = """Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in 
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum."""

textarea = Textarea(value=area, layout=Layout(height="8em", width="30em"))
dropdown = Dropdown(description='Choice', options=['foo', 'bar'])

HBox( [VBox([dropdown, 
             HBox([Button(description='A'), Button(description='B')])]), 
        textarea])

In [ ]: